/**
 * @author banglong
 * @date 2016/10/19
 */
define(['avalon', 'Layer', 'tools', 'rootPath', 'depsSelectDialog', 'GoodsSelectDialog', 'Condition', 'Conditions', 'chooseCondition',
    'text!../html/index/cardManager/cardListTemp.html!strip', 'cardManagerApi', 'conditionsUtils', 'MoreSelectDialog',
    'CardDetailInfo', 'RadioSelectDialog', 'laydatev5'
  ],
  function (avalon, layer, tools, rootPath, depsSelectDialog, GoodsSelectDialog, Condition, Conditions,
    chooseCondition, htmlTemp, api, conditionsUtils, MoreSelectDialog, CardDetailInfo, RadioSelectDialog,laydate) {
    var CardManager = function () {

      var self = this;
      var runtimeParam;
      var getRuntimeParam = function () {
        return {
          chooseSupplier: [], // 选中的 供应商生产厂商数据
          chooseManufacturer: [], // 选中的生产厂商数据
          timeObj: {}
        };
      };

      var cardManagerVm;
      var getVmOption = function () {
        return {
          $id: 'cardManager',
          breadcrumb: '',
          iKsdm:false,//科室代码是否为设备科
          cardNumber: '', //卡片号
          goodsName: '', //物品名称
          goodsID: '', //物品代码
          goodsBookName: '', //账册名称
          goodsBookID: '', //账册id

          barcode: '', //条形码
          deptAccountName: '', //账户名称
          deptAccountID: '', //账户ID
          buyStartDate: '', // 购置时间
          buyEndDate: '', // 购置时间

          scrapStatus: '', //报废情况
          finishDisCardTime:'',//报废时间
          machineName: '',
          machineCode: '', //仪器编码
          manufacturer: '', //生产厂商
          supplier: '', //供应商
          isGive: '', //是否供应

          nullifyStatus: '', //作废情况
          applyStartDate: '', //报关时间
          applyEndDate: '', //报关时间
          priceStart: '', //价格段
          priceEnd: '', //价格段
          skNumber: '', //申康编号
          showPages: true, // 显示分页

          header: ['卡片号', '物品代码', '物品名称', '规格型号', '价格', '总价', '领用科室', '仪器编号', '机身号',
            '购置时间', '供货商', '经费来源', '物品状态', '报废时间', '是否作废', '折旧年限', '已折旧月份', '当月折旧金额', '累积折旧金额','维保时间'
          ],
          row: ['CardNumber', 'GoodsCode', 'GoodsName', 'GoodsSpec', 'RmbPrice', 'TotalPrice', 'DrawDeptAccountName', 'InstrumentCode', 'MachineNumber',
            'PurchaseTime', 'SupplierName', 'BudgetSourceName', 'GoodsStatusString', 'DiscardTime', 'IsCardsNullified',
            'Zjnx', 'Yzjyf', 'Dyzjje', 'Ljzjje','WarrantyDate','CardID','GoodsBookID'
          ],
          data: [],
          tableComponentsID: ['cardManager_table'],

          chooseGoods: function (e) {
            tools.throttle(runtimeParam.timeObj, function () {
              new GoodsSelectDialog().init({
                Openparm: runtimeParam.Openparm,
                isGYKS: false,
                CurrentDeptAccount: runtimeParam.currentDept,
                ProviderDeptAccount: runtimeParam.providerDept,
                searchValue: cardManagerVm.goodsName, //初始的查询信息
                getAll: true,
                condition: conditionsUtils.getGoodsCondition({
                  GoodsBookID: cardManagerVm.goodsBookID
                }),
                GoodsBookID: cardManagerVm.goodsBookID,
                pushChooseGoods: function (data) { // 选择物品
                  cardManagerVm.goodsName = data.GoodsName;
                  cardManagerVm.goodsID = data.GoodsID;
                }
              });
            });
          },

          // 选取账册
          chooseCondition: function (e) {
            tools.throttle(runtimeParam.timeObj, function () {
              var param = {
                type: 1
              };
              param.chooseConditionsFunc = function (condition) {
                cardManagerVm.goodsBookName = condition.GoodsBookName;
                cardManagerVm.goodsBookID = condition.GoodsBookID;
              };
              param.searchValue = cardManagerVm.goodsBookName;
              chooseCondition.init(param);
            });
          },

          // 多选 选取供货商/生产商
          chooseShop: function (e, type) {
            tools.throttle(runtimeParam.timeObj, function () {
              var condition = {};
              var chooseDataArray = [];
              switch (type) {
                case 0: // 生产厂商
                  (function () {
                    var IsManufacture = new Condition("b.IsManufacture", null, "Equal", true, "Boolean");
                    var isOne = new Condition("1", null, "Equal", 1, "Int32");
                    condition = new Conditions([IsManufacture, isOne], "AND");
                    chooseDataArray = runtimeParam.chooseManufacturer.concat();
                  }());
                  break;
                case 1: //供应商
                  (function () {
                    var IsAgent = new Condition("b.IsAgent", null, "Equal", true, "Boolean");
                    var isOne = new Condition("1", null, "Equal", 1, "Int32");
                    condition = new Conditions([IsAgent, isOne], "AND");
                    chooseDataArray = runtimeParam.chooseSupplier.concat();
                  }());
                  break;
              }

              new MoreSelectDialog().init({
                header: ['名称', '拼音码', '地址', '联系人', '联系电话1', '联系电话2', '联系电话3'],
                row: ['SupplierName', 'PyCode', 'Address', 'ContactPerson', 'PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3'],
                className: 'SupplierManager',
                method: 'GetSuppliersForWeb',
                condition: condition,
                chooseDataArray: chooseDataArray,
                handleChooseData: function (dataArr) {
                  if (Array.isArray(dataArr)) {
                    var name = '';
                    dataArr.forEach(function (data) {
                      name += data.SupplierName + ';'
                    });
                    if (type === 0) {
                      cardManagerVm.manufacturer = name;
                      runtimeParam.chooseManufacturer = dataArr.concat();
                    } else {
                      cardManagerVm.supplier = name;
                      runtimeParam.chooseSupplier = dataArr.concat();
                    }
                  }
                }
              });
            });
          },
          repairBill:function(){
        	  var dom =document.querySelector('.table-fixed-body-tr.active');
        	  if(!dom){
        		  tools.handleError('请选择卡片!!');
        		  return false;
        	  }
        	  var len = dom.cells.length;
        	  dom.cells[len-2].style.width='20px';
        	  dom.cells[len-2].style.display= 'none';
        	  dom.cells[len-1].style.width='20px';
        	  dom.cells[len-1].style.display= 'none';
        	  if(dom.cells[12].innerText!=='正常'){
	    		  tools.handleError('请选择正常状态的卡片!!');
	    		  return false;
        	  }
        	 if(dom.cells[len-3].innerText !=='' || new Date() < new Date(dom.cells[len-3].innerText)){
	    		  tools.handleError('请走维修合同!!');
	    		  return false;
        	  }
        	if(dom.cells[len-1].innerText !=='000000000000HH' && dom.cells[len-1].innerText !=='000000000000GG' ){
	    		  tools.handleError('请选择设备科卡片!!');
	    		  return false;
        	  }
        	 setPopup();
        	var cardID = dom.cells[len-2].innerText;
       	  	var user = JSON.parse(localStorage.getItem('currentUser')) || {};
       	  	var userID = user.Ygid;
        	 $('#repairReason .btn-sure').click(function(){
        		 var reason = $('#repairReason .reason').val();
        		 api.getRepairBill({
           		  className: 'RepairManager',
                     method: 'GenerateRepairBill',
                     cardID:cardID,
                     userID:userID,
                     repairReason:reason
	           	  }).then(function(res){
	           		 if(res.issuccess===0){
	           			 $('#popUp,#repairReason').remove();
	           			var url = rootPath.getRootPath() +'repairBill/repairBill.html?billSN='+res.result;
	                	  var myElement = document.createElement("iframe")
	                	  myElement.src = url;
	                	  myElement.id ="repair-bill-container";
	                	  myElement.style.width = "100%";
	                	  myElement.style.height = "100%";
	                	  myElement.style.position = "fixed";
	                	  myElement.style.left = "0";
	                	  myElement.style.top = "0";
	                	  myElement.style.zIndex = "100";
	                	  document.body.appendChild(myElement);
	           		  }
	           	  })
        	 })
        	 $('#repairReason .btn-cancel').click(function(){
        		 $('#popUp,#repairReason').remove();
        		 tools.handleError('你已取消维修单申请!!');
	    		  return false;
        	 })
        	 
          },
          search: function () {
            var param = Object.assign({}, cardManagerVm.$model, {
              chooseSupplier: runtimeParam.chooseSupplier.concat(), // 选中的 供应商生产厂商数据
              chooseManufacturer: runtimeParam.chooseManufacturer.concat() // 选中的生产厂商数据
            });
            var condition = conditionsUtils.getCardManagerCondition(param);
            // 记录查询条件 可以将查询结果导出
            runtimeParam.queryParam = {
              className: 'CardManager',
              method: 'GetCardsQuery',
              condition: JSON.stringify(condition),
              StartTime:null,
              EndTime:null,
              IsAttachment:false
            };

            var loadIndex = layer.load();
            api.getCardsQuery({
              className: 'CardManager',
              method: 'GetCardsQuery',
              condition: JSON.stringify(condition),
              StartTime:null,
              EndTime:null,
              IsAttachment:false
              
            }).then(function (jsonResult) {

              if (jsonResult.issuccess !== 0) {
                return Promise.reject('获取信息失败');
              }

              var result = JSON.parse(jsonResult.result);
              result.forEach(function (data) {
                switch (data.GoodsStatusStr) {
                  case 'zc':
                    data.GoodsStatusString = '正常';
                    break;
                  case 'bf':
                    data.GoodsStatusString = '报废';
                    break;
                  case 'db':
                    data.GoodsStatusString = '待报废';
                    break;
                }
                data.IsCardsNullified = data.IsCardsNullified ? '是' : '否';
              });
              cardManagerVm.data.splice(0, cardManagerVm.data.length);
              cardManagerVm.data.pushArray(result);
              layer.close(loadIndex);

            })['catch'](function (ex) {
              layer.close(loadIndex);
              tools.handleError(ex);
            });
            // 清除 排序效果
            $(document.body).trigger("clearOrder");
          },

          exportExcel: function () {
              if (cardManagerVm.data.length <= 0 || !runtimeParam.queryParam) {
                tools.handleError("请确认查询结果不为空");
                return;
              }
              // 导出excel
              var excelParam = runtimeParam.queryParam;
                var fieldValueName = cardManagerVm.row.$model.slice(0,20);
              if (tools.isIEByActiveObject()) {
                tools.DownLoadFile({
                  url: rootPath.getRootPath() + "export/cardListInfo",//stockExcel
                  data: {
                    name: '卡片查询',
                    className: excelParam.className,
                    method: excelParam.method,
                    condition: encodeURIComponent(excelParam.condition),
                    StartTime:null,
                    EndTime:null,
                    IsAttachment:false,
                    fieldName: JSON.parse(JSON.stringify(cardManagerVm.header.$model)).join(','),
                    fieldValueName: JSON.parse(JSON.stringify(fieldValueName)).join(',')
                  }
                });
              } else {
                var url = rootPath.getRootPath() + "export/cardListInfo";//cardListInfo
                url += '?name=' + encodeURIComponent(encodeURIComponent('卡片查询'));
                url += '&className=' + encodeURIComponent(encodeURIComponent(excelParam.className));
                url += '&method=' + encodeURIComponent(encodeURIComponent(excelParam.method));
                url += '&condition=' + encodeURIComponent(encodeURIComponent(excelParam.condition));
                url+='&StartTime=null';
                url+='&EndTime=null';
                url+='&IsAttachment='+encodeURIComponent(false);
                url += '&fieldName=' + encodeURIComponent(encodeURIComponent(JSON.parse(JSON.stringify(cardManagerVm.header.$model)).join(',')));
                url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(JSON.parse(JSON.stringify(fieldValueName)).join(',')));
                
                window.location.href = url;
              }
            },

          back: function () {
            var main = document.querySelector('#main');
            main.removeChild(tools.getFirstElementChild(main));
            runtimeParam.checkBreadcrumb();
            runtimeParam.showMenu();
            self.destroy();
          },

          viewCardDetail: function (card) {
            var param = {
              card: card
            };
            new CardDetailInfo().init(param);
          },

          // 选择仪器编码
          chooseInstrumentCode: function () {
            tools.throttle(runtimeParam.timeObj, function () {
              var conditionParam = {
                goodsBookID: cardManagerVm.goodsBookID,
                searchValue: cardManagerVm.machineName
              };
              var condition = conditionsUtils.selectCode(conditionParam);
              new RadioSelectDialog().init({
                header: ['账册名称', '仪器编码', '仪器编码名称', '拼音码', '当前最大号'],
                row: ['GoodsBookName', 'MainInstrumentCode', 'MainInstrumentName', 'PyCode', 'MaxInstrumentNumber'],
                searchNameIndex: 2,
                requestParam: {
                  className: 'CardManager',
                  method: 'SelectCode',
                  condition: JSON.stringify(condition)
                },
                getConditionFunc: conditionsUtils.selectCode,
                conditionParam: conditionParam,
                choose: function (data) {
                  cardManagerVm.machineName = data.MainInstrumentName;
                  cardManagerVm.machineCode = data.MainInstrumentCode;
                }
              });
            });
          }
        };
      };
      
      //弹框
      function setPopup(){
    	  var popUp = '<div id="popUp" style="position: fixed; top: 0;left: 0;width:100%;height:100%;z-index: 8; background-color:#333;opacity: 0.2;"></div>';
    	  	popUp += '<div id="repairReason"  style="position: fixed; top: 20%;left: 50%;z-index: 10;margin-left:-140px;width: 280px;background-color: #fff; padding: 5px; ">';
	  		popUp += '<h2 style="height: 32px;line-height: 32px;font-size: 16px;color: #333;margin: 0;padding: 0;">请填写维修原因:</h2>';
	  		popUp +='<textarea class="reason" style="width:100%;height:65px;font-size:14px;"></textarea>';
	  		popUp += '<button type="button" class="btn btn-primary btn-sure">确定</button><button type="button" class="btn btn-warning btn-cancel" style="float: right;">取消</button >';
	  		popUp += '</div>'
	  		$("#main").find('#popUp,#repairReason').remove();
	  		$("#main").append(popUp);
      };
      //生成维修单
      function getRepariBill(cardID,userID){
    	  api.getRepairBill({
    		  className: 'RepairManager',
              method: 'GenerateRepairBill',
              cardID:cardID,
              userID:userID
    	  }).then(function(res){
    		  if(res.issuccess===0){
    			  if(res.result && res.result!==''){
    				  var url = rootPath.getRootPath() +'repairBill/repairBill.html?billSN='+res.result;
                	  var myElement = document.createElement("iframe")
                	  myElement.src = url;
                	  myElement.id ="repair-bill-container";
                	  myElement.style.width = "100%";
                	  myElement.style.height = "100%";
                	  myElement.style.position = "fixed";
                	  myElement.style.left = "0";
                	  myElement.style.top = "0";
                	  myElement.style.zIndex = "100";
                	  document.body.appendChild(myElement);
    			  }
    			  
    		  }
    	  })
      };
      // 供应科室 详细信息
      function getProviderDeptInfo(runtimeParam) {
        api.getOutDTODept({
          className: 'OrganizationManager',
          method: 'GetOutDTODept',
          ksdm: runtimeParam.Openparm.ProviderDept
        }).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject('获取信息失败');
          }
          runtimeParam.providerDept = JSON.parse(jsonResult.result);
          cardManagerVm.iKsdm=(runtimeParam.providerDept.Ksdm=='0030100');
        })['catch'](function (ex) {
          tools.handleError(ex)
        });
      }

      function initDateControl() {
        setTimeout(function () {
        laydate.render({
            elem: '#buyStartDate'
          });
        laydate.render({
            elem: '#buyEndDate'
          });
        laydate.render({
            elem: '#applyStartDate'
          });
        laydate.render({
            elem: '#applyEndDate'
          });
        laydate.render({
              elem: '#finishDisCardTime'
              ,type: 'year'
            });
        }, 300);
        
      }

      function setVmWatch(cardManagerVm) {
        cardManagerVm.$watch('goodsBookName', function (value) {
          if (!value) {
            cardManagerVm.goodsBookID = '';
          }
        });
        cardManagerVm.$watch('machineName', function (value) {
          if (!value) {
            cardManagerVm.machineCode = '';
          }
        });
      }

      this.init = function ($main, param) {
        $main.append(htmlTemp);

        cardManagerVm = tools.initAvalonVm(avalon, getVmOption(), ".card-manager");
        cardManagerVm.breadcrumb = param.breadcrumb;

        runtimeParam = getRuntimeParam();
        runtimeParam.showMenu = param.showMenu;
        runtimeParam.checkBreadcrumb = param.checkBreadcrumb;
        runtimeParam.Openparm = param.Openparm; // 初始化参数
        runtimeParam.currentDept = JSON.parse(localStorage.getItem('deptInfo'));

        cardManagerVm.deptAccountName = runtimeParam.currentDept.Ksmc.trim();
        cardManagerVm.deptAccountID = runtimeParam.currentDept.DeptAccountID;
        cardManagerVm.scrapStatus = 'zc';
        cardManagerVm.nullifyStatus = 'yx';
        cardManagerVm.isGive = 'all';

        getProviderDeptInfo(runtimeParam); // 供应科室 详细信息
        initDateControl();
        setVmWatch(cardManagerVm);
        tools.bindDestroyMethod(self.destroy);
        // 设置分页
//        setTimeout(function() {
//          cardManagerVm.showPages = false;
//        }, 0)
      };

      this.destroy = function () {
        runtimeParam = null;
        cardManagerVm = null;
        tools.destroy(getVmOption());
      };
    };

    return CardManager;
  }
);